package com.hippo4j.executor.manage;

import com.gj.model.ThreadPoolParameter;
import com.hippo4j.executor.DynamicThreadPoolWrapper;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程全局管理器
 * 客户端这侧使用
 */
public class GlobalThreadPoolManage {

    private static final Map<String, ThreadPoolParameter> PARAMETER_INFO_MAP = new ConcurrentHashMap<>();

    private static final Map<String, DynamicThreadPoolWrapper> EXECUTOR_MAP = new ConcurrentHashMap<>();


    //根据线程池Id得到对应的DynamicThreadPoolWrapper对象
    public static DynamicThreadPoolWrapper getExecutorService(String threadPoolId) {
        return EXECUTOR_MAP.get(threadPoolId);
    }

    //根据线程池Id得到ThreadPoolExecutor的方法
    public static ThreadPoolExecutor getExecutor(String threadPoolId) {
        return Optional.ofNullable(EXECUTOR_MAP.get(threadPoolId)).map(each -> each.getExecutor()).orElse(null);
    }

    //根据线程池Id得到对用的线程池核心参数对象的方法
    public static ThreadPoolParameter getPoolParameter(String threadPoolId) {
        return PARAMETER_INFO_MAP.get(threadPoolId);
    }


    //把线程池核心参数信息和线程池包装对象交给线程池全局管理器管理的方法
    public static void register(String threadPoolId, ThreadPoolParameter threadPoolParameter, DynamicThreadPoolWrapper executor) {
        registerPool(threadPoolId, executor);
        registerPoolParameter(threadPoolId, threadPoolParameter);
    }


    public static void registerPool(String threadPoolId, DynamicThreadPoolWrapper executor) {
        EXECUTOR_MAP.put(threadPoolId, executor);
    }


    public static void registerPoolParameter(String threadPoolId, ThreadPoolParameter threadPoolParameter) {
        PARAMETER_INFO_MAP.put(threadPoolId, threadPoolParameter);
    }

}
